package javaweb.selectcclass.test.controller;

import javaweb.selectcclass.test.entity.Course;
import javaweb.selectcclass.test.entity.Submit;
import javaweb.selectcclass.test.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Controller
public class HomeController {

    static User user = new User("何先生","1825121000","2018","软件工程","计算机科学与技术");
    static List<Course> list = Arrays.asList(
            new Course("计算机网络", "01"),
            new Course("计算机组成原理", "02"),
            new Course("操作系统", "03")
    );

    @GetMapping("/home")
    public String home(Model model){
        model.addAttribute("user",user);
        return "home";
    }

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("/select")
    public String select(Model model) {
        model.addAttribute("courses", list);
        return "select";
    }

    @PostMapping("/select")
    public String send(@Valid Submit submit, Errors errors, Model model) {
        if(errors.hasErrors()) {
            model.addAttribute("err", "err");
            return select(model);
        }
        model.addAttribute("user",user);
        List<String> stringList = submit.getCourses();
        List<Course> courseList = new LinkedList<>();
        for(Course c : list){
            for(String s : stringList){
                if(c.getId().equals(s)){
                    courseList.add(c);
                    break;
                }
            }
        }
        model.addAttribute("course",courseList);
        return "send";
    }
}
